import 'dart:math';

import 'package:http/http.dart' as http;
import 'package:http/retry.dart';
import 'dart:convert';

void main() {
  sendPostRequestWithRetry();
}

Future<void> sendPostRequestWithRetry() async {
  final url = Uri.parse('http://10.0.0.100');
  final jsonData = jsonEncode({'name': 'John', 'age': 30});

  final maxRetries = 5;
  final retryDelay = Duration(seconds: 5);

  final client = RetryClient(
    http.Client(),
    retries: maxRetries,
    when: (response) => response.statusCode != 200,
    onRetry: (request, response, retryCount) {
      print('Request failed with status code: ${response?.statusCode}. Retrying ($retryCount/$maxRetries) in ${retryDelay.inSeconds} seconds...');
    },
    delay: (int retryCount) => const Duration(milliseconds: 500) * pow(1.5, retryCount),
  );

  var request = http.Request('POST', url)..body = jsonData;

  try {
    var response = await client.send(request);
    if (response.statusCode == 200) {
      var jsonResponse = await utf8.decodeStream(response.stream);
      print('Response status: ${response.statusCode}');
      print('Response body: $jsonResponse');
    } else {
      print('Failed to send request after $maxRetries retries. Reason: ${response.reasonPhrase}');
    }
  } on Exception catch (e) {
    print('Failed to send request after $maxRetries retries. Reason: $e');
  } finally {
    client.close();
  }
}
